<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a{
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;

            /* 禁止用户选中 */
            -webkit-user-select:none ;
            
        }
    </style>
    <script>

        window.onload = function() {

            var oDiv = document.querySelector('.a') ;
            

            // 拖拽：鼠标按下盒子，然后移动鼠标

            oDiv.onmousedown = function(e) {
                var e = e || event ;
                // 获取鼠标按下的时候，鼠标在盒子中的位置
                var gapX = e.offsetX ;
                var gapY = e.offsetY ;


                document.onmousemove = function(e) {
                    var e = e || event ;
                    var x = e.x - gapX ;
                    var y = e.y - gapY;
                    oDiv.style.cssText = `left:${x}px;top:${y}px;`
                }


                document.onmouseup = function() {
                    // 清除鼠标移动事件
                    document.onmousemove = null ;
                    // console.log(666);
                    // 把自己也清除  --- 因为当我们不点小方块的时候，这个鼠标抬起事件也会被触发
                    document.onmouseup = null ;
                }
            }

        }

    </script>
</head>
<body>
    <div class="a">111111111111111111</div>
</body>
</html>